﻿using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using AppCommon;
using BO;
using Model;

public partial class admincenter_CategoryManager : Page
{
    public static SqlConnection Connection = new SqlConnection(ConfigurationManager.ConnectionStrings["defaultConnection"].ConnectionString);

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Session[Constants.S_ADMIN_USER] != null)
            {
                // Ok
            }
            else
            {
                Response.Redirect("~/admincenter/");
            }

            FillGrid("LastDateUpdated", false);
        }
    }


    /// <summary>
    /// Method : FillGrid 
    /// Use : Bind data to gridview
    /// </summary>
    /// <param name="SortExpression"></param>
    /// <param name="IsSorting"></param>
    public void FillGrid(string SortExpression, bool IsSorting)
    {
        var dt = new DataTable();
        dt.Columns.Add("Id");
        dt.Columns.Add("Name");
        dt.Columns.Add("LastDateUpdated");
        dt.Columns.Add("LastUpdatedBy");
        dt.Columns.Add("Status", typeof(bool));

        // Lay chuoi ket noi CSDL
        Connection.Open();
        const string query = "SELECT * FROM [PrivateBlog].[dbo].[Categories]";
        var dataAdapter = new SqlDataAdapter(query, Connection);
        dataAdapter.Fill(dt);
        Connection.Close(); // dong ket noi       

        var dv = dt.DefaultView;
        if (ViewState["SortExpression"] != null && ViewState["SortDirection"] != null)
        {
            if (IsSorting)
            {
                if (ViewState["SortExpression"].ToString() == SortExpression)
                {
                    if (ViewState["SortDirection"].ToString() == "ASC")
                        ViewState["SortDirection"] = "DESC";
                    else
                        ViewState["SortDirection"] = "ASC";
                }
                else
                {
                    ViewState["SortExpression"] = SortExpression;
                    ViewState["SortDirection"] = "ASC";
                }
            }
        }
        else
        {
            ViewState["SortExpression"] = SortExpression;
            ViewState["SortDirection"] = "ASC";
        }

        dv.Sort = ViewState["SortExpression"] + " " + ViewState["SortDirection"];
        gv.DataSource = dv.ToTable();
        gv.DataBind();
    }

    /// <summary>
    /// Event OnPageIndexChanging="gv_PageIndexChanging" on GridView
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void gv_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gv.PageIndex = e.NewPageIndex;
        FillGrid(ViewState["SortExpression"].ToString(), false);
    }

    /// <summary>
    /// Event OnSorting="gv_Sorting" on GridView
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void gv_Sorting(object sender, GridViewSortEventArgs e)
    {
        FillGrid(e.SortExpression, true);
    }

    /// <summary>
    /// Xu ly Add / Update du lieu tuong ung
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnThemVao_OnClick(object sender, EventArgs e)
    {
        var id = tbId.Text.Trim();
        var name = tbName.Text.Trim();
        if (name.Equals("") || id.Equals(""))
        {
            return;
        }
        var trangthai = cbTrangThai.Checked;
        var categoryBo = new CategoryBO();
        var category = new Category {Id = id, Name = name, LastUpdatedBy = "admin", Status = Convert.ToInt32(trangthai)};

        var stringBuilder = new StringBuilder();
        if (categoryBo.AddCategory(category) > 0)
        {
            panelTrangthai.Visible = true;
            // 
            stringBuilder.Append("<p class=\"alert alert-success\">");
            stringBuilder.Append(
                "<button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×</button>");
            stringBuilder.Append("<i class=\"fa fa-info\"></i> Đã thêm chuyên mục thành công");
            stringBuilder.Append("</p>");
            litResult.Text = stringBuilder.ToString();
            // Cap nhat lai du lieu
            FillGrid(ViewState["SortExpression"].ToString(), false);
            // Reset cac field
            tbName.Text = "";
            tbId.Text = "";
            cbTrangThai.Checked = false;
        }
        else
        {
            panelTrangthai.Visible = true;
            // 
            stringBuilder.Append("<p class=\"alert alert-danger\">");
            stringBuilder.Append("<i class=\"fa fa-error\"></i> Thêm chuyên mục thất bại");
            stringBuilder.Append("</p>");
            litResult.Text = stringBuilder.ToString();
        }
    }

    protected void gv_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("Edit"))
        {
            try
            {                
                var id = Convert.ToInt32(e.CommandArgument.ToString());                                
                hiddenId.Value = e.CommandArgument.ToString();
                //// Truy van du lieu de lay tu bang VYC-07
                //Connection.Open();
                //var query = "SELECT * FROM [VYCTravel].[dbo].[VYC-07] WHERE [dbo].[VYC-07].[Id] = " + id;
                //var dataAdapter = new SqlDataAdapter(query, Connection);
                //var dataTable = new DataTable("VYC07");
                //dataAdapter.Fill(dataTable);

                //if (dataTable.Rows.Count > 0)
                //{
                //    tbName.Text = dataTable.Rows[0]["Ten"].ToString();
                //    cbTrangThai.Checked = (bool)dataTable.Rows[0]["TrangThai"];
                //}
            }
            catch (Exception)
            {
                Connection.Close();
                throw;
            }
        }
        if (e.CommandName.Equals("Delete"))
        {
            try
            {
                hiddenId.Value = e.CommandArgument.ToString();
            }
            catch (Exception)
            {

                throw;
            }
        }
    }

    protected void lbEdit_OnCommand(object sender, CommandEventArgs e)
    {        
        var id = e.CommandArgument;
    }    


    
}